const express = require('express');
const router = express.Router();
const _multer = require('multer');
const _path = require('path');
const _fs = require('fs').promises;
const auth = require('../middleware/auth');
const { ImportExportRecord } = require('../models');
const importExportController = require('../controllers/importExportController');

// 确保上传目录存在
const uploadDir = _path.join(process.cwd(), 'uploads');
_fs.mkdir(uploadDir, { recursive: true }).catch(console.error);

// 配置文件上传 - 改用内存存储
const storage = _multer.memoryStorage();

const upload = _multer({ 
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024 // 限制10MB
  },
  fileFilter: function (req, file, cb) {
    const allowedTypes = ['.xlsx', '.xls', '.csv'];
    const ext = _path.extname(file.originalname).toLowerCase();
    if (allowedTypes.includes(ext)) {
      cb(null, true);
    } else {
      cb(new Error('不支持的文件格式'));
    }
  }
});

// 获取记录列表
router.get('/list', importExportController.getRecords);

// 删除单条记录
router.delete('/record/:id', importExportController.deleteRecord);

// 获取可选字段列表
router.get('/available-fields', importExportController.getAvailableFields);

// 下载导入模板
router.post('/template', importExportController.getTemplate);

// 预览文件
router.post('/preview', upload.single('file'), importExportController.previewImport);

// 修改导入路由
router.post('/import', upload.single('file'), importExportController.confirmImport);

// 导出数据
router.get('/export', importExportController.createExport);

// 下载导出文件
router.get('/download/exports/:filename', importExportController.downloadExport);

// 下载导入文件
router.get('/download/imports/:filename', importExportController.downloadImport);

// 下载历史文件
router.get('/history-file/:id', importExportController.downloadHistoryFile);

// 清理临时文件
router.post('/clean-temp-file', importExportController.cleanTempFile);

// 批量删除记录
router.post('/batch-delete', importExportController.deleteRecords);

// 设置日志保留天数
router.post('/retention-days', importExportController.setRetentionDays);

// 获取日志保留天数
router.get('/retention-days', importExportController.getRetentionDays);

module.exports = router; 